
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;

namespace Articles
{
	public class ArticleRssBizRules : Syrinx.BaseBizRules
	{
		public IBizObjList getRssLeafNodeOptions(IApplication app, IRuleContext context)
		{
			return app.appData.get("RssLeafNodeOptions") as IBizObjList;
		}

		public IBizObjList getCompanyRssChannels(IApplication app, IRuleContext context, Swaf.BGuid.Guid companyId)
		{
			if (companyId == null)
				companyId = ActiveCompanyId;

			context.put("companyId", companyId);
			IBizObjList feeds = app.appData.get("DA.Articles.GetCompanyRssChannels", context) as IBizObjList;
			return feeds;
		}

		public void updateCompanyRssChannel(IApplication app, IRuleContext context, IBizObj feed)
		{
			if (!feed.isDirty("companyId") || feed.get("companyId") == null)
				feed.put("companyId", ActiveCompanyId);
			if (feed.isNew)
				app.appData.put("DA.Articles.AddRssChannel", feed);
			else
				app.appData.put("DA.Articles.UpdateRssChannel", feed);
		}

		public void deleteCompanyRssChannel(IApplication app, IRuleContext context, Swaf.BGuid.Guid feedId)
		{
			context.put("id", feedId);
			app.appData.put("DA.Articles.DeleteRssChannel", context);
		}

		/// <summary>
		/// This bizrule will generate a string of RSS Xml for all of the articles within the given article id
		/// passed.  
		/// </summary>
		/// <remarks>If a user is not logged into the application when the RSS feed is requested, it will be done
		/// under the anonymous user of the company.  The company used is based on the specific URL used to get
		/// the RSS or the root company if a generic URL was used. For more information on the RSS 2.0
		/// specification that this bizrule uses see http://www.rssboard.org/rss-specification.</remarks>
		/// <param name="title">The title to use for the RSS Xml document</param>
		/// <param name="link">The HTTP link to get this RSS</param>
		/// <param name="description">The description to use for the Rss Xml document</param>
		/// <param name="albumLink">The prefix HTTP URI to use for each album link.</param>
		/// <returns>The RSS Xml</returns>
		public string getArticleRss(IApplication app, IRuleContext context, string rssUniqueId, Uri link)
		{
			string rssXml = "";
			IBizObj rssFeed = null;
			Swaf.BGuid.Guid articleId = Swaf.BGuid.Guid.TryParse(rssUniqueId);
			if (articleId == null)
				articleId = context.RuleGroup.execute(context, "getArticleIdFromUniqueTitle", rssUniqueId).CallResults as Swaf.BGuid.Guid;
			if (articleId != null)
			{
				context.put("id", articleId);
				rssFeed = app.appData.get("DA.Articles.GetRssFeed", context) as IBizObj;
			}
			if (rssFeed != null)
			{
				string baseLoc = link.AbsoluteUri.Substring(0, link.AbsoluteUri.IndexOf(link.AbsolutePath));
				StringWriter s = new StringWriter();
				XmlTextWriter xml = new XmlTextWriter(s);
				//xml.WriteStartDocument();
				xml.WriteStartElement("rss");
				xml.WriteAttributeString("version", "2.0");
				xml.WriteStartElement("channel");
				xml.WriteElementString("link", link.ToString());

				context.put("BizObjType", "Article");
				context.put("parentId", articleId);
				context.put("includeSelf", true);
				context.put("entireTree", rssFeed.get("entireTree"));
				context.put("listDetailLevel", DetailLevel.basicDetails);
				IResults rc = app.ruleMgr.execute("getArticles", context, (IBizObj)null);
				IBizObjList articles = rc.CallResults as IBizObjList;
				if (articles != null)
					for (int pos = 0; pos < articles.numElements; pos++)
					{
						IBizObj article = articles[pos];
						if (pos == 0)
						{
							xml.WriteElementString("title", article.get("title").ToString());
							xml.WriteElementString("description", article.get("summary").ToString());
						}
						else
						{
							if ((Convert.ToInt32(rssFeed.get("leafNodes"))!=0) && pos < articles.numElements - 1)
							{
								IBizObj nextArticle = articles[pos + 1];
								int curDepth = (int)article.get("depth");
								int nextDepth = (int)nextArticle.get("depth");
								if (nextDepth > curDepth)
									continue;
							}
							xml.WriteStartElement("item");
							xml.WriteElementString("title", article.get("title").ToString());
							xml.WriteElementString("link",
								app.resMgr.resolve(String.Format("{0}$CmpSetting(sitePath)$/articles/{1}_{2}.aspx", baseLoc, rssUniqueId, article.get("uniqueId"))));
							xml.WriteElementString("description", article.get("summary").ToString());
							//xml.WriteElementString("pubDate", album.get("dateUpdated").ToString());
							xml.WriteEndElement();
						}
					}
				xml.WriteEndElement();
				xml.WriteEndElement();
				xml.Close();
				s.Close();
				rssXml = s.ToString();
			}
			return rssXml;
		}
	}
}
